/*!
 * VideoElementPlayer
 *
 * Creates a controller bar for HTML5 <video> tags.
 *
 *
 */
if (typeof jQuery != 'undefined') {
	mejs.$ = jQuery;
} else if (typeof ender != 'undefined') {
	mejs.$ = ender;
}
(function ($) {

	// Default player values
	mejs.MepDefaults = {
		// Url to poster (to fix iOS 3.x)
		poster: '',
		// When the video is ended, we can show the poster.
		showPosterWhenEnded: true,
		// Default if the <video width> is not specified
		defaultVideoWidth: 480,
		// Default if the <video height> is not specified
		defaultVideoHeight: 270,
		// If set, overrides <video width>
		videoWidth: -1,
		// If set, overrides <video height>
		videoHeight: -1,

		// Default amount to move back when back key is pressed
		defaultSeekBackwardInterval: function(player, media) {
                           return ((player.options.duration > 0) ? (player.options.duration * 0.05) : (media.duration * 0.05));
		},
                        
		// Default amount to move forward when forward key is pressed
		defaultSeekForwardInterval: function(player, media) {
			return ((player.options.duration > 0) ? (player.options.duration * 0.05) : (media.duration * 0.05));
		},
		// Initial volume when the player starts (overrided by user cookie)
		startVolume: 0.8,
		// Resize to media dimensions
		enableAutosize: true,
		// Forces the hour marker (##:00:00)
		alwaysShowHours: false,
		// Automatically calculate the width of the progress bar based on the sizes of other elements
		autosizeProgress : true,
		// Hide controls when playing and mouse is not over the video
		alwaysShowControls: false,
		// Display the video control
		hideVideoControlsOnLoad: false,
                // Enable click video element to toggle play/pause
                clickToPlayPause: true,
		// Features
		features: ['playpause','current','progress','duration','tracks','volume','fullscreen', 'captioncustomiser'],

		// Turns keyboard support on and off for this instance
		enableKeyboard: true,

		// When this player starts, it will pause other players
		pauseOtherPlayers: true,

		// Array of keyboard actions
		keyActions: [
                                {
                                    keys: [
                                        32, // SPACE
                                        179 // GOOGLE play/pause button
                                    ],
                                    action: function(player, media)
                                    {
                                        if (media.paused || media.ended)
                                        {
                                            player.play();
                                        } 
                                        else 
                                        {
                                            player.pause();
                                        }
                                    }
				},
				{
                                    keys: [38], // UP
                                    action: function(player, media)
                                    {
                                        player.container.find('.mejs-volume-slider').css('display','block');
                                        player.showControls();
                                        player.startControlsTimer();

                                        var newVolume = Math.min(media.volume + 0.1, 1);
                                        media.setVolume(newVolume);
                                    }
				},
				{
                                    keys: [40], // DOWN
                                    action: function(player, media)
                                    {
                                        player.container.find('.mejs-volume-slider').css('display','block');
                                        player.showControls();
                                        player.startControlsTimer();

                                        var newVolume = Math.max(media.volume - 0.1, 0);
                                        media.setVolume(newVolume);
                                    }
				},
				{
                                    keys: [
                                                    37, // LEFT
                                                    227 // Google TV rewind
                                    ],
                                    action: function(player, media) {
                                                    if ((player.options.duration > 0) || (media.duration > 0)) {
                                                                    player.showControls();
                                                                    player.startControlsTimer();

                                                                    // 5%
                                                                    var newTime = Math.max(player.currentTime - player.options.defaultSeekBackwardInterval(player, media), 0);
                                                                    player.setCurrentTime(newTime);
                                                    }
                                    }
				},
				{
                                    keys: [
                                                    39, // RIGHT
                                                    228 // Google TV forward
                                    ],
                                    action: function(player, media) {
                                                    if ((player.options.duration > 0) || (media.duration > 0)) {
                                                                    player.showControls();
                                                                    player.startControlsTimer();

                                                                    // 5%
                                                                    var newTime = Math.min(player.currentTime + player.options.defaultSeekForwardInterval(player, media), (player.options.duration > 0) ? player.options.duration : media.duration);
                                                                    player.setCurrentTime(newTime);
                                                    }
                                    }
				},
				{
                                    keys: [70], // F
                                    action: function(player, media)
                                    {
                                        if (typeof player.enterFullScreen != 'undefined') {
                                                        if (player.isFullScreen) {
                                                                        player.exitFullScreen();
                                                        } else {
                                                                        player.enterFullScreen();
                                                        }
                                        }
                                    }
                                },
                                {
                                    keys: [77], // M
                                    action: function(player, media) {
                                        player.container.find('.mejs-volume-slider').css('display','block');
                                        player.showControls();
                                        player.startControlsTimer();
                                        
                                        if (player.media.muted) {
                                            player.setMuted(false);
                                        } else {
                                            player.setMuted(true);
                                        }
                                    }
				}
		]
	};

	mejs.mepIndex = 0;

	mejs.players = {};

	// Wraps a MediaElement object in player controls
	mejs.MediaElementPlayer = function(node, o) {

                if ( !(this instanceof mejs.MediaElementPlayer) ) {
			return new mejs.MediaElementPlayer(node, o);
		}

		var t = this;

		// These will be reset after the MediaElement.success fires
		t.$media = t.$node = $(node);
		t.node = t.media = t.$media[0];

		// Check for existing player
		if (typeof t.node.player != 'undefined') {
			return t.node.player;
		} else {
			// Attach player to DOM node for reference
			t.node.player = t;
		}


		// Try to get options from data-mejsoptions
		if (typeof o == 'undefined') {
			o = t.$node.data('mejsoptions');
		}

		// Extend default options
		t.options = $.extend({},mejs.MepDefaults,o);

		// Unique ID
		t.id = 'mep_' + mejs.mepIndex++;

		// Add to player array
		mejs.players[t.id] = t;

		// Start
		t.init();

		return t;
	};

	// Actual player
	mejs.MediaElementPlayer.prototype = {

		hasFocus: false,

		controlsAreVisible: true,

		init: function() {

			var
				t = this,
				mf = mejs.MediaFeatures,
				// Options for MediaElement (shim)
				meOptions = $.extend(true, {}, t.options, {
					success: function(media, domNode) { t.meReady(media, domNode); },
					error: function(e) { t.handleError(e);}
				}),
				tagName = t.media.tagName.toLowerCase();

			t.isDynamic = tagName !== 'video';

                        // Remove native controls
                        t.$media.removeAttr('controls');

                        // Build container
                        t.container =
                                $('<div id="' + t.id + '" class="mejs-container ' + (mejs.MediaFeatures.svg ? 'svg' : 'no-svg') + '">'+
                                        '<div class="mejs-inner">'+
                                                '<div class="mejs-mediaelement"></div>'+
                                                '<div class="mejs-layers"></div>'+
                                                '<div class="mejs-controls"></div>'+
                                                '<div class="mejs-clear"></div>'+
                                        '</div>' +
                                '</div>')
                                .addClass(t.$media[0].className)
                                .insertBefore(t.$media);

                        // Add classes for user and content
                        t.container.addClass(
                                (mf.isAndroid ? 'mejs-android ' : '') +
                                (mf.isiOS ? 'mejs-ios ' : '') +
                                (mf.isiPad ? 'mejs-ipad ' : '') +
                                (mf.isiPhone ? 'mejs-iphone ' : '') +
                                ('mejs-video ')
                        );


                        // Move the <video> tag into the right spot
                        if (mf.isiOS) {

                                // Sadly, you can't move nodes in iOS, so we have to destroy and recreate it!
                                var $newMedia = t.$media.clone();

                                t.container.find('.mejs-mediaelement').append($newMedia);

                                t.$media.remove();
                                t.$node = t.$media = $newMedia;
                                t.node = t.media = $newMedia[0]

                        } else {

                                // Normal way of moving it into place (doesn't work on iOS)
                                t.container.find('.mejs-mediaelement').append(t.$media);
                        }

                        // Find parts
                        t.controls = t.container.find('.mejs-controls');
                        t.layers = t.container.find('.mejs-layers');
                        
                        // Determine the size

                        /* size priority:
                                (1) videoWidth (forced),
                                (2) style="width;height;"
                                (3) width attribute,
                                (4) defaultVideoWidth (for unspecified cases)
                        */


                        if (t.options.videoWidth > 0 || t.options.videoWidth.toString().indexOf('%') > -1) {
                                t.width = t.options.videoWidth;
                        } else if (t.media.style.width !== '' && t.media.style.width !== null) {
                                t.width = t.media.style.width;
                        } else if (t.media.getAttribute('width') !== null) {
                                t.width = t.$media.attr('width');
                        } else {
                                t.width = t.options.defaultVideoWidth;
                        }

                        if (t.options.videoHeight > 0 || t.options.videoHeight.toString().indexOf('%') > -1) {
                                t.height = t.options.videoHeight;
                        } else if (t.media.style.height !== '' && t.media.style.height !== null) {
                                t.height = t.media.style.height;
                        } else if (t.$media[0].getAttribute('height') !== null) {
                                t.height = t.$media.attr('height');
                        } else {
                                t.height = t.options.defaultVideoHeight;
                        }

                        // Set the size
                        t.setPlayerSize(t.width, t.height);

			// create MediaElement shim
			mejs.MediaElement(t.$media[0], meOptions);

			if (typeof(t.container) != 'undefined' && t.controlsAreVisible){
			    // Controls are shown when loaded
			    t.container.trigger('controlsshown');
			}
		},
                        
		showControls: function(doAnimation) {
			var t = this;

			doAnimation = typeof doAnimation == 'undefined' || doAnimation;

			if (t.controlsAreVisible)
				return;

			if (doAnimation) {
				t.controls
					.css('visibility','visible')
					.stop(true, true).fadeIn(200, function() {
					      t.controlsAreVisible = true;
					      t.container.trigger('controlsshown');
					});

				// Any additional controls people might add and want to hide
				t.container.find('.mejs-control')
					.css('visibility','visible')
					.stop(true, true).fadeIn(200, function() {t.controlsAreVisible = true;});

			} else {
				t.controls
					.css('visibility','visible')
					.css('display','block');

				// Any additional controls people might add and want to hide
				t.container.find('.mejs-control')
					.css('visibility','visible')
					.css('display','block');

				t.controlsAreVisible = true;
				t.container.trigger('controlsshown');
			}

			t.setControlsSize();

		},

		hideControls: function(doAnimation) {
			var t = this;

			doAnimation = typeof doAnimation == 'undefined' || doAnimation;

			if (!t.controlsAreVisible || t.options.alwaysShowControls)
				return;

			if (doAnimation) {
				// Fade out main controls
				t.controls.stop(true, true).fadeOut(200, function() {
					$(this)
						.css('visibility','hidden')
						.css('display','block');

					t.controlsAreVisible = false;
					t.container.trigger('controlshidden');
				});

				// Any additional controls people might add and want to hide
				t.container.find('.mejs-control').stop(true, true).fadeOut(200, function() {
					$(this)
						.css('visibility','hidden')
						.css('display','block');
				});
			} else {

				// Hide main controls
				t.controls
					.css('visibility','hidden')
					.css('display','block');

				// Hide others
				t.container.find('.mejs-control')
					.css('visibility','hidden')
					.css('display','block');

				t.controlsAreVisible = false;
				t.container.trigger('controlshidden');
			}
		},

		controlsTimer: null,

		startControlsTimer: function(timeout) {

			var t = this;

			timeout = typeof timeout != 'undefined' ? timeout : 1500;

			t.killControlsTimer('start');

			t.controlsTimer = setTimeout(function() {
				t.hideControls();
				t.killControlsTimer('hide');
			}, timeout);
		},

		killControlsTimer: function(src) {

			var t = this;

			if (t.controlsTimer !== null) {
				clearTimeout(t.controlsTimer);
				delete t.controlsTimer;
				t.controlsTimer = null;
			}
		},

		controlsEnabled: true,

		disableControls: function() {
			var t= this;

			t.killControlsTimer();
			t.hideControls(false);
			this.controlsEnabled = false;
		},

		enableControls: function() {
			var t= this;

			t.showControls(false);

			t.controlsEnabled = true;
		},


		// Sets up all controls and events
		meReady: function(media, domNode) {


			var t = this,
				mf = mejs.MediaFeatures,
				autoplayAttr = domNode.getAttribute('autoplay'),
				autoplay = !(typeof autoplayAttr == 'undefined' || autoplayAttr === null || autoplayAttr === 'false'),
				featureIndex,
				feature;

			t.media = media;
			t.domNode = domNode;

                        t.buildposter(t, t.controls, t.layers, t.media);
                        t.buildkeyboard(t, t.controls, t.layers, t.media);
                        t.buildoverlays(t, t.controls, t.layers, t.media);

                        // Grab for use by features
                        t.findTracks();

                        // Add user-defined features/controls
                        for (featureIndex in t.options.features) {
                                feature = t.options.features[featureIndex];
                                if (t['build' + feature]) {
                                        try {
                                                t['build' + feature](t, t.controls, t.layers, t.media);
                                        } catch (e) {

                                        }
                                }
                        }

                        t.container.trigger('controlsready');

                        // Reset all layers and controls
                        t.setPlayerSize(t.width, t.height);
                        t.setControlsSize();


                        // Controls fade
                        if (mejs.MediaFeatures.hasTouch) {

                                t.$media.bind('touchstart', function() {

                                        // Toggle controls
                                        if (t.controlsAreVisible) {
                                                t.hideControls(false);
                                        } else {
                                                if (t.controlsEnabled) {
                                                        t.showControls(false);
                                                }
                                        }
                                });

                        } else {

                                // Create callback here since it needs access to current MediaElement object
                                mejs.MediaElementPlayer.prototype.clickToPlayPauseCallback = function() {

                                        if (t.options.clickToPlayPause) {
                                                if (t.media.paused) {
                                                        t.media.play();
                                                } else {
                                                        t.media.pause();
                                                }
                                        }
                                };

                    // Click to play/pause
                    t.media.addEventListener('click', t.clickToPlayPauseCallback, false);

                                // Show/hide controls
                                t.container
                                        .bind('mouseenter mouseover', function () {
                                                if (t.controlsEnabled) {
                                                        if (!t.options.alwaysShowControls) {
                                                                t.killControlsTimer('enter');
                                                                t.showControls();
                                                                t.startControlsTimer(2500);
                                                        }
                                                }
                                        })
                                        .bind('mousemove', function() {
                                                if (t.controlsEnabled) {
                                                        if (!t.controlsAreVisible) {
                                                                t.showControls();
                                                        }
                                                        //t.killControlsTimer('move');
                                                        if (!t.options.alwaysShowControls) {
                                                                t.startControlsTimer(2500);
                                                        }
                                                }
                                        })
                                        .bind('mouseleave', function () {
                                                if (t.controlsEnabled) {
                                                        if (!t.media.paused && !t.options.alwaysShowControls) {
                                                                t.startControlsTimer(1000);
                                                        }
                                                }
                                        });
                        }

                        if(t.options.hideVideoControlsOnLoad) {
                                t.hideControls(false);
                        }

                        // Check for autoplay
                        if (autoplay && !t.options.alwaysShowControls) {
                                t.hideControls();
                        }

                        // Resizer
                        if (t.options.enableAutosize) {
                                t.media.addEventListener('loadedmetadata', function(e) {
                                        // If the <video height> was not set and the options.videoHeight was not set resize to the real dimensions.
                                        if (t.options.videoHeight <= 0 && t.domNode.getAttribute('height') === null && !isNaN(e.target.videoHeight)) {
                                                t.setPlayerSize(e.target.videoWidth, e.target.videoHeight);
                                                t.setControlsSize();
                                                t.media.setVideoSize(e.target.videoWidth, e.target.videoHeight);
                                        }
                                }, false);
                        }

                        // EVENTS

                        // FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
                        media.addEventListener('play', function() {
                                var playerIndex;

                                // Go through all other players
                                for (playerIndex in mejs.players) {
                                        var p = mejs.players[playerIndex];
                                        if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
                                                p.pause();
                                        }
                                        p.hasFocus = false;
                                }

                                t.hasFocus = true;
                        },false);


                        // Ended for all
                        t.media.addEventListener('ended', function (e) {

                                t.media.pause();

                                if (t.setCurrentRail) {
                                        t.setCurrentRail();
                                }

                                if (!t.options.alwaysShowControls && t.controlsEnabled) {
                                        t.showControls();
                                }
                        }, false);

                        // Resize on the first play
                        t.media.addEventListener('loadedmetadata', function(e) {
                                if (t.updateDuration) {
                                        t.updateDuration();
                                }
                                if (t.updateCurrent) {
                                        t.updateCurrent();
                                }

                                if (!t.isFullScreen) {
                                        t.setPlayerSize(t.width, t.height);
                                        t.setControlsSize();
                                }
                        }, false);


                        // Webkit has trouble doing this without a delay
                        setTimeout(function () {
                                t.setPlayerSize(t.width, t.height);
                                t.setControlsSize();
                        }, 50);

                        // Adjust controls whenever window sizes (used to be in fullscreen only)
                        t.globalBind('resize', function() {

                                // Don't resize for fullscreen mode
                                if ( !(t.isFullScreen || (mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen)) ) {
                                        t.setPlayerSize(t.width, t.height);
                                }

                                // Always adjust controls
                                t.setControlsSize();
                        });

			// Force autoplay for HTML5
			if (autoplay) {
				t.play();
			}


			if (t.options.success) {

				if (typeof t.options.success == 'string') {
					window[t.options.success](t.media, t.domNode, t);
				} else {
					t.options.success(t.media, t.domNode, t);
				}
			}
		},

		handleError: function(e) {
			var t = this;

			t.controls.hide();

			// Tell user that the file cannot be played
			if (t.options.error) {
				t.options.error(e);
			}
		},

		setPlayerSize: function(width,height) {
			var t = this;

			if (typeof width != 'undefined') {
				t.width = width;
			}

			if (typeof height != 'undefined') {
				t.height = height;
			}

			// Detect 100% mode - use currentStyle for IE since css() doesn't return percentages
                        if (t.height.toString().indexOf('%') > 0 || t.$node.css('max-width') === '100%' || parseInt(t.$node.css('max-width').replace(/px/,''), 10) / t.$node.offsetParent().width() === 1 || (t.$node[0].currentStyle && t.$node[0].currentStyle.maxWidth === '100%')) {

				// Do we have the native dimensions yet?
				var
					nativeWidth = (t.media.videoWidth && t.media.videoWidth > 0) ? t.media.videoWidth : t.options.defaultVideoWidth,
					nativeHeight = (t.media.videoHeight && t.media.videoHeight > 0) ? t.media.videoHeight : t.options.defaultVideoHeight,
					parentWidth = t.container.parent().closest(':visible').width(),
					newHeight = !t.options.autosizeProgress ? parseInt(parentWidth * nativeHeight/nativeWidth, 10) : nativeHeight;

				if (t.container.parent()[0].tagName.toLowerCase() === 'body') { // && t.container.siblings().count == 0) {
					parentWidth = $(window).width();
					newHeight = $(window).height();
				}

				if ( newHeight != 0 && parentWidth != 0 ) {
					// Set outer container size
					t.container
						.width(parentWidth)
						.height(newHeight);

					// Set native <video>.
					t.$media.add(t.container.find('.mejs-shim'))
						.width('100%')
						.height('100%');

					// Set the layers
					t.layers.children('.mejs-layer')
						.width('100%')
						.height('100%');
				}


			} else {

				t.container
					.width(t.width)
					.height(t.height);

				t.layers.children('.mejs-layer')
					.width(t.width)
					.height(t.height);

			}

			// Special case for big play button so it doesn't go over the controls area
			var playLayer = t.layers.find('.mejs-overlay-play'),
				playButton = playLayer.find('.mejs-overlay-button');

			playLayer.height(t.container.height() - t.controls.height());
			playButton.css('margin-top', '-' + (playButton.height()/2 - t.controls.height()/2).toString() + 'px'  );

		},

		setControlsSize: function() {
			var t = this,
				usedWidth = 0,
				railWidth = 0,
				rail = t.controls.find('.mejs-time-rail'),
				total = t.controls.find('.mejs-time-total'),
				current = t.controls.find('.mejs-time-current'),
				loaded = t.controls.find('.mejs-time-loaded'),
				others = rail.siblings();


			// Allow the size to come from custom CSS
			if (t.options && !t.options.autosizeProgress) {
				railWidth = parseInt(rail.css('width'));
			}

			// Attempt to autosize
			if (railWidth === 0 || !railWidth) {

				// Find the size of all the other controls besides the rail
				others.each(function() {
					var $this = $(this);
					if ($this.css('position') != 'absolute' && $this.is(':visible')) {
						usedWidth += $(this).outerWidth(true);
					}
				});

				// Fit the rail into the remaining space
				railWidth = t.controls.width() - usedWidth - (rail.outerWidth(true) - rail.width());
			}

			// Outer area
			rail.width(railWidth);
			// Dark space
			total.width(railWidth - (total.outerWidth(true) - total.width()));

			if (t.setCurrentRail)
				t.setCurrentRail();
		},


		buildposter: function(player, controls, layers, media) {
			var t = this,
				poster =
				$('<div class="mejs-poster mejs-layer">' +
				'</div>')
					.appendTo(layers),
				posterUrl = player.$media.attr('poster');

			// Priority goes to option (this is useful if you need to support iOS 3.x (iOS completely fails with poster)
			if (player.options.poster !== '') {
				posterUrl = player.options.poster;
			}

			// Second, try the real poster
			if (posterUrl !== '' && posterUrl != null) {
				t.setPoster(posterUrl);
			} else {
				poster.hide();
			}

			media.addEventListener('play',function() {
				poster.hide();
			}, false);

			if(player.options.showPosterWhenEnded){
				media.addEventListener('ended',function() {
					poster.show();
				}, false);
			}
		},

		setPoster: function(url) {
			var t = this,
				posterDiv = t.container.find('.mejs-poster'),
				posterImg = posterDiv.find('img');

			if (posterImg.length == 0) {
				posterImg = $('<img width="100%" height="100%" />').appendTo(posterDiv);
			}

			posterImg.attr('src', url);
			posterDiv.css({'background-image' : 'url(' + url + ')'});
		},

		buildoverlays: function(player, controls, layers, media) {
                        var t = this;

			var
			loading =
				$('<div class="mejs-overlay mejs-layer">'+
					'<div class="mejs-overlay-loading"><span></span></div>'+
				'</div>')
				.hide() // start out hidden
				.appendTo(layers),
			error =
				$('<div class="mejs-overlay mejs-layer">'+
					'<div class="mejs-overlay-error"></div>'+
				'</div>')
				.hide()
				.appendTo(layers),
			// This needs to come last so it's on top
			bigPlay =
				$('<div class="mejs-overlay mejs-layer mejs-overlay-play">'+
					'<div class="mejs-overlay-button"></div>'+
				'</div>')
				.appendTo(layers)
                                .click(function() {
                                    if (t.options.clickToPlayPause)
                                    {
                                        if (media.paused)
                                        {
                                            media.play();    
                                        }
                                        else
                                        {
                                            media.pause();
                                        }
                                    }
                                });	

			// Show/hide big play button
			media.addEventListener('play',function() {
				bigPlay.hide();
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
				error.hide();
			}, false);

			media.addEventListener('playing', function() {
				bigPlay.hide();
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
				error.hide();
			}, false);

			media.addEventListener('seeking', function() {
				loading.show();
				controls.find('.mejs-time-buffering').show();
			}, false);

			media.addEventListener('seeked', function() {
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
			}, false);

			media.addEventListener('pause',function() {
				if (!mejs.MediaFeatures.isiPhone) {
					bigPlay.show();
				}
			}, false);

			media.addEventListener('waiting', function() {
				loading.show();
				controls.find('.mejs-time-buffering').show();
			}, false);

			// Show/hide loading
			media.addEventListener('loadeddata',function() {
				loading.show();
				controls.find('.mejs-time-buffering').show();
			}, false);
                        
			media.addEventListener('canplay',function() {
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
			}, false);

			// Error handling
			media.addEventListener('error',function() {
				loading.hide();
				controls.find('.mejs-time-buffering').hide();
				error.show();
				error.find('mejs-overlay-error').html("Error loading this resource");
			}, false);
		},

		buildkeyboard: function(player, controls, layers, media) {

				var t = this;

				// Listen for key presses
				t.globalBind('keydown', function(e) {

						if (player.hasFocus && player.options.enableKeyboard) {

								// Find a matching key
								for (var i=0, il=player.options.keyActions.length; i<il; i++) {
										var keyAction = player.options.keyActions[i];

										for (var j=0, jl=keyAction.keys.length; j<jl; j++) {
												if (e.keyCode == keyAction.keys[j]) {
														e.preventDefault();
														keyAction.action(player, media, e.keyCode);
														return false;
												}
										}
								}
						}

						return true;
				});

				// Check if someone clicked outside a player region, then kill its focus
				t.globalBind('click', function(event) {
						if ($(event.target).closest('.mejs-container').length == 0) {
								player.hasFocus = false;
						}
				});

		},

		findTracks: function() {
			var t = this,
				tracktags = t.$media.find('track');

			// Store for use by plugins
			t.tracks = [];
			tracktags.each(function(index, track) {

				track = $(track);

				t.tracks.push({
					srclang: (track.attr('srclang')) ? track.attr('srclang').toLowerCase() : '',
					src: track.attr('src'),
					kind: track.attr('kind'),
					label: track.attr('label') || '',
					entries: [],
					isLoaded: false
				});
			});
		},
                        
		changeSkin: function(className) {
			this.container[0].className = 'mejs-container ' + className;
			this.setPlayerSize(this.width, this.height);
			this.setControlsSize();
		},
                        
		play: function()
                {
                    this.media.play();
		},
                        
		pause: function() {
			try {
				this.media.pause();
			} catch (e) {}
		},
                        
		load: function()
                {
                    this.media.load();
		},
                        
		setMuted: function(muted) {
			this.media.setMuted(muted);
		},
                        
		setCurrentTime: function(time) {
			this.media.setCurrentTime(time);
		},
                        
		getCurrentTime: function() {
			return this.media.currentTime;
		},
                        
		setVolume: function(volume) {
			this.media.setVolume(volume);
		},
                        
		getVolume: function() {
			return this.media.volume;
		},
                        
		setSrc: function(src) {
			this.media.setSrc(src);
		},
                        
		remove: function() {
			var t = this, featureIndex, feature;

			// Invoke features cleanup
			for (featureIndex in t.options.features) {
				feature = t.options.features[featureIndex];
				if (t['clean' + feature]) {
					try {
						t['clean' + feature](t);
					} catch (e) {
                                            
					}
				}
			}

			// Grab video and put it back in place
			if (!t.isDynamic) {
				t.$media.prop('controls', true);
				t.$node.clone().show().insertBefore(t.container);
				t.$node.remove();
			} else {
				t.$node.insertBefore(t.container);
			}

			// Remove the player from the mejs.players object.
			delete mejs.players[t.id];

			t.container.remove();
			t.globalUnbind();
			delete t.node.player;
		}
	};

	(function(){
		var rwindow = /^((after|before)print|(before)?unload|hashchange|message|o(ff|n)line|page(hide|show)|popstate|resize|storage)\b/;

		function splitEvents(events, id) {
			// Add player ID as an event namespace so it's easier to unbind them all later
			var ret = {d: [], w: []};
			$.each((events || '').split(' '), function(k, v){
				var eventname = v + '.' + id;
				if (eventname.indexOf('.') === 0) {
					ret.d.push(eventname);
					ret.w.push(eventname);
				}
				else {
					ret[rwindow.test(v) ? 'w' : 'd'].push(eventname);
				}
			});
			ret.d = ret.d.join(' ');
			ret.w = ret.w.join(' ');
			return ret;
		}

		mejs.MediaElementPlayer.prototype.globalBind = function(events, data, callback) {
			var t = this;
			events = splitEvents(events, t.id);
			if (events.d) $(document).bind(events.d, data, callback);
			if (events.w) $(window).bind(events.w, data, callback);
		};

		mejs.MediaElementPlayer.prototype.globalUnbind = function(events, callback) {
			var t = this;
			events = splitEvents(events, t.id);
			if (events.d) $(document).unbind(events.d, callback);
			if (events.w) $(window).unbind(events.w, callback);
		};
	})();

	// Turn into jQuery plugin
	if (typeof jQuery != 'undefined') {
		jQuery.fn.mediaelementplayer = function (options) {
			if (options === false) {
				this.each(function () {
					var player = jQuery(this).data('mediaelementplayer');
					if (player) {
						player.remove();
					}
					jQuery(this).removeData('mediaelementplayer');
				});
			}
			else {
				this.each(function () {
					jQuery(this).data('mediaelementplayer', new mejs.MediaElementPlayer(this, options));
				});
			}
			return this;
		};
	}

	$(document).ready(function() {
		// Auto enable using JSON attribute
		$('.mejs-player').mediaelementplayer();
	});

	// Push out to window
	window.MediaElementPlayer = mejs.MediaElementPlayer;

})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		playpauseText: 'Play/Pause'
	});

	// PLAY/PAUSE BUTTON
	$.extend(MediaElementPlayer.prototype, {
		buildplaypause: function(player, controls, layers, media) {
			var 
				t = this,
				play = 
				$('<div class="mejs-button mejs-playpause-button mejs-play" >' +
					'<button type="button" aria-controls="' + t.id + '" title="' + t.options.playpauseText + '" aria-label="' + t.options.playpauseText + '"></button>' +
				'</div>')
				.appendTo(controls)
				.click(function(e) {
					e.preventDefault();
				
					if (media.paused) {
						media.play();
					} else {
						media.pause();
					}
					
					return false;
				});

			media.addEventListener('play',function() {
				play.removeClass('mejs-play').addClass('mejs-pause');
			}, false);
                        
			media.addEventListener('playing',function() {
				play.removeClass('mejs-play').addClass('mejs-pause');
			}, false);

			media.addEventListener('pause',function() {
				play.removeClass('mejs-pause').addClass('mejs-play');
			}, false);
                        
			media.addEventListener('paused',function() {
				play.removeClass('mejs-pause').addClass('mejs-play');
			}, false);
		}
	});
	
})(mejs.$);

(function($) {
	// Progress Bar
	$.extend(MediaElementPlayer.prototype, {
		buildprogress: function(player, controls, layers, media) {

			$('<div class="mejs-time-rail">'+
                                        '<span class="mejs-time-total">'+
					'<span class="mejs-time-buffering"></span>'+
					'<span class="mejs-time-current"></span>'+
					'<span class="mejs-time-handle"></span>'+
					'<span class="mejs-time-float">' + 
						'<span class="mejs-time-float-current">00:00</span>' + 
						'<span class="mejs-time-float-corner"></span>' + 
					'</span>'+
				'</span>'+
			'</div>')
				.appendTo(controls);
				controls.find('.mejs-time-buffering').hide();

			var 
				t = this,
				total = controls.find('.mejs-time-total'),
				current  = controls.find('.mejs-time-current'),
				handle  = controls.find('.mejs-time-handle'),
				timefloat  = controls.find('.mejs-time-float'),
				timefloatcurrent  = controls.find('.mejs-time-float-current'),
				handleMouseMove = function (e) {
                                        // Mouse position relative to the object
                                        var x = e.pageX,
                                        offset = total.offset(),
                                        width = total.outerWidth(true),
                                        percentage = 0,
                                        newTime = 0,
                                        pos = 0;


					if (media.duration || t.options.duration) {
						if (x < offset.left) {
							x = offset.left;
						} else if (x > width + offset.left) {
							x = width + offset.left;
						}
						
						pos = x - offset.left;
						percentage = (pos / width);
                                                
                                                newTime = percentage * (t.options.duration ? t.options.duration : media.duration);

						// Seek to where the mouse is
						if (mouseIsDown && newTime !== t.currentTime) {
                                                        t.setCurrentTime(newTime);
                                                }

						// Position floating time box
						if (!mejs.MediaFeatures.hasTouch) {
								timefloat.css('left', pos);
								timefloatcurrent.html( mejs.Utility.secondsToTimeCode(newTime) );
								timefloat.show();
						}
					}
				},
				mouseIsDown = false,
				mouseIsOver = false;

			// Handle clicks
			total
				.bind('mousedown', function (e) {
                                    // Only handle left clicks
                                    if (e.which === 1 || e.which === 0) {
						mouseIsDown = true;
						handleMouseMove(e);
						t.globalBind('mousemove.dur', function(e) {
							handleMouseMove(e);
						});
						t.globalBind('mouseup.dur', function (e) {
							mouseIsDown = false;
							timefloat.hide();
							t.globalUnbind('.dur');
						});
						return false;
					}
				})
				.bind('mouseenter', function(e) {
					mouseIsOver = true;
					t.globalBind('mousemove.dur', function(e) {
						handleMouseMove(e);
					});
					if (!mejs.MediaFeatures.hasTouch) {
						timefloat.show();
					}
				})
				.bind('mouseleave',function(e) {
					mouseIsOver = false;
					if (!mouseIsDown) {
						t.globalUnbind('.dur');
						timefloat.hide();
					}
				});

			// Loading
			media.addEventListener('progress', function (e) {
				player.setCurrentRail(e);
			}, false);

			// Current time
			media.addEventListener('timeupdate', function(e) {
				player.setCurrentRail(e);
			}, false);
			
			
			// Store for later use
			t.total = total;
			t.current = current;
			t.handle = handle;
		},
		setCurrentRail: function() {

			var t = this;
		
                        if (t.currentTime && (t.options.duration > 0) || (t.media.duration > 0)) {
                            // Update bar
                            if (t.total && t.handle) {
                                    var 
                                            newWidth = Math.round(t.total.width() * t.currentTime / (t.options.duration ? t.options.duration : t.media.duration)),
                                            handlePos = newWidth - Math.round(t.handle.outerWidth(true) / 2);

                                    t.current.width(newWidth);
                                    t.handle.css('left', handlePos);
                            }
                        }

		}
	});
})(mejs.$);
// Source Chooser Plugin
(function($) {

	$.extend(mejs.MepDefaults, {
		sourcechooserText: 'Source Chooser'
	});

	$.extend(MediaElementPlayer.prototype, {
		buildsourcechooser: function(player, controls, layers, media) {

			var t = this;

			player.sourcechooserButton =
				$('<div class="mejs-button mejs-sourcechooser-button">'+
					'<button type="button" aria-controls="' + t.id + '" title="' + t.options.sourcechooserText + '" aria-label="' + t.options.sourcechooserText + '"></button>'+
					'<div class="mejs-sourcechooser-selector">'+
						'<ul>'+
						'</ul>'+
					'</div>'+
				'</div>')
					.appendTo(controls)

					// hover
					.hover(function() {
						$(this).find('.mejs-sourcechooser-selector').css('visibility','visible');
					}, function() {
						$(this).find('.mejs-sourcechooser-selector').css('visibility','hidden');
					})

					// handle clicks to the language radio buttons
					.delegate('input[type=radio]', 'click', function() {
						src = this.value;

						if (media.currentSrc != src) {
							currentTime = media.currentTime;
							paused = media.paused;
							media.setSrc(src);
							media.load();
							media.addEventListener('loadedmetadata', function(e){
				                this.currentTime = currentTime;
				            }, true);
				            media.addEventListener('canplay', function(e){
				            	if (!paused) {
					            	this.play();
					            }
				            }, true);
						}
					});

			// add to list
			for (i in media.children) {
				src = media.children[i];
				if (src.nodeName === 'SOURCE' && (media.canPlayType(src.type) == 'probably' || media.canPlayType(src.type) == 'maybe')) {
					player.addSourceButton(src.src, src.title, src.type, media.src == src.src);
				}
			}

		},

		addSourceButton: function(src, label, type, isCurrent) {
			var t = this;
			if (label === '' || label == undefined) {
				label = src;
			}
			type = type.split('/')[1];

			t.sourcechooserButton.find('ul').append(
				$('<li>'+
					'<input type="radio" name="' + t.id + '_sourcechooser" id="' + t.id + '_sourcechooser_' + label + type + '" value="' + src + '" ' + (isCurrent ? 'checked="checked"' : '') + ' />'+
					'<label for="' + t.id + '_sourcechooser_' + label + type + '">' + label + ' (' + type + ')</label>'+
				'</li>')
			);

			t.adjustSourcechooserBox();

		},

		adjustSourcechooserBox: function() {
			var t = this;
			// adjust the size of the outer box
			t.sourcechooserButton.find('.mejs-sourcechooser-selector').height(
				t.sourcechooserButton.find('.mejs-sourcechooser-selector ul').outerHeight(true)
			);
		}
	});

})(mejs.$);

(function($) {
	
	// Options
	$.extend(mejs.MepDefaults, {
		timeAndDurationSeparator: '<span> | </span>'
	});


	// Time
	$.extend(MediaElementPlayer.prototype, {
		buildcurrent: function(player, controls, layers, media) {
			var t = this;
			
			$('<div class="mejs-time">'+
					'<span class="mejs-currenttime">' + (player.options.alwaysShowHours ? '00:00:00' : '00:00')
					+ '</span>'+ '</div>')
					.appendTo(controls);
			
			t.currenttime = t.controls.find('.mejs-currenttime');
		},


		buildduration: function(player, controls, layers, media) {
			var t = this;
			
			if (controls.children().last().find('.mejs-currenttime').length > 0) {
				$(t.options.timeAndDurationSeparator +
					'<span class="mejs-duration">' + 
						(t.options.duration > 0 ? 
							mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.media.duration > 3600) :
				   			(player.options.alwaysShowHours ? '00:00:00' : '00:00') 
				   		) + 
					'</span>')
					.appendTo(controls.find('.mejs-time'));
			} else {

				// Add class to current time
				controls.find('.mejs-currenttime').parent().addClass('mejs-currenttime-container');
				
				$('<div class="mejs-time mejs-duration-container">'+
					'<span class="mejs-duration">' + 
						(t.options.duration > 0 ? 
							mejs.Utility.secondsToTimeCode(t.options.duration, t.options.alwaysShowHours || t.options.duration > 3600) :
				   			(player.options.alwaysShowHours ? '00:00:00' : '00:00') 
				   		) + 
					'</span>' +
				'</div>')
				.appendTo(controls);
			}
			
			t.durationD = t.controls.find('.mejs-duration');

                        media.addEventListener('timeupdate',function() {
                            player.updateDuration();
                        }, false);
		},
		
		updateCurrent:  function() {
            
			var t = this;

			if (t.currenttime) {
                            t.currenttime.html(mejs.Utility.secondsToTimeCode(t.currentTime, t.options.alwaysShowHours || (t.options.duration ? t.options.duration > 3600 : t.media.duration > 3600)));
                        }
		},
		
		updateDuration: function() {   
			var t = this;

			//Toggle the long video class if the video is longer than an hour.
                        if(t.options.duration > 0)
                            t.container.toggleClass("mejs-long-video", t.options.duration > 3600);
                        else
                            t.container.toggleClass("mejs-long-video", t.media.duration > 3600);
			
			if (t.durationD && (t.options.duration > 0 || t.media.duration > 0)) {
				t.durationD.html(mejs.Utility.secondsToTimeCode((t.options.duration ? t.options.duration : t.media.duration), t.options.alwaysShowHours));
			}	
                }
	});

})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		muteText: 'Mute Toggle',
		hideVolumeOnTouchDevices: true,
	});

	$.extend(MediaElementPlayer.prototype, {
		buildvolume: function(player, controls, layers, media) {
				
			// Android and iOS don't support volume controls
			if (mejs.MediaFeatures.hasTouch && this.options.hideVolumeOnTouchDevices)
				return;
			
			var t = this,
				mute =
				
				// Vertical Volume
				$('<div class="mejs-button mejs-volume-button mejs-mute">'+
					'<button type="button" aria-controls="' + t.id + '" title="' + t.options.muteText + '" aria-label="' + t.options.muteText + '"></button>'+
					'<div class="mejs-volume-slider">'+ // Outer background
						'<div class="mejs-volume-total"></div>'+ // Line background
						'<div class="mejs-volume-current"></div>'+ // Current volume
						'<div class="mejs-volume-handle"></div>'+ // Handle
					'</div>'+
				'</div>')
					.appendTo(controls),
			volumeSlider = t.container.find('.mejs-volume-slider, .mejs-horizontal-volume-slider'),
			volumeTotal = t.container.find('.mejs-volume-total, .mejs-horizontal-volume-total'),
			volumeCurrent = t.container.find('.mejs-volume-current, .mejs-horizontal-volume-current'),
			volumeHandle = t.container.find('.mejs-volume-handle, .mejs-horizontal-volume-handle'),

			positionVolumeHandle = function(volume, secondTry) {

				if (!volumeSlider.is(':visible') && typeof secondTry == 'undefined') {
					volumeSlider.show();
					positionVolumeHandle(volume, true);
					volumeSlider.hide()
					return;
				}
			
				// Correct to 0-1
				volume = Math.max(0,volume);
				volume = Math.min(volume,1);					
				
				// Adjust mute button style
				if (volume == 0) {
					mute.removeClass('mejs-mute').addClass('mejs-unmute');
				} else {
					mute.removeClass('mejs-unmute').addClass('mejs-mute');
				}				

				// Position slider   
                                var 

                                // Height of the full size volume slider background
                                totalHeight = volumeTotal.height(),

                                // Top/left of full size volume slider background
                                totalPosition = volumeTotal.position(),

                                // The new top position based on the current volume
                                newTop = totalHeight - (totalHeight * volume);

                                // Handle
                                volumeHandle.css('top', Math.round(totalPosition.top + newTop - (volumeHandle.height() / 2)));

                                // Show the current visibility
                                volumeCurrent.height(totalHeight - newTop );
                                volumeCurrent.css('top', totalPosition.top + newTop);
			},
                                
			handleVolumeMove = function(e) {
				
				var volume = null,
					totalOffset = volumeTotal.offset();
				
				// Calculate the new volume based on the mouse position
                                var

                                railHeight = volumeTotal.height(),
                                totalTop = parseInt(volumeTotal.css('top').replace(/px/,''),10),
                                newY = e.pageY - totalOffset.top;

                                volume = (railHeight - newY) / railHeight;

                                // The controls hide themselves (usually when mouse moves too far up)
                                if (totalOffset.top == 0 || totalOffset.left == 0)
                                        return;
				
				// Ensure the volume isn't outside 0-1
				volume = Math.max(0,volume);
				volume = Math.min(volume,1);
				
				// Position the slider and handle			
				positionVolumeHandle(volume);
				
				// Set the media object (this will trigger the volumechanged event)
				if (volume == 0) {
					media.setMuted(true);
				} else {
					media.setMuted(false);
				}
				media.setVolume(volume);			
			},
			mouseIsDown = false,
			mouseIsOver = false;

			// SLIDER
			
			mute
				.hover(function() {
					volumeSlider.show();
					mouseIsOver = true;
				}, function() {
					mouseIsOver = false;	
						
					if (!mouseIsDown)	{
						volumeSlider.hide();
					}
				});
			
			volumeSlider
				.bind('mouseover', function() {
					mouseIsOver = true;	
				})
				.bind('mousedown', function (e) {
					handleVolumeMove(e);
					t.globalBind('mousemove.vol', function(e) {
						handleVolumeMove(e);
					});
					t.globalBind('mouseup.vol', function () {
						mouseIsDown = false;
						t.globalUnbind('.vol');

						if (!mouseIsOver) {
							volumeSlider.hide();
						}
					});
					mouseIsDown = true;
						
					return false;
				});


			// MUTE button
			mute.find('button').click(function() {
				media.setMuted( !media.muted );
			});

			// Listen for volume change events from other sources
			media.addEventListener('volumechange', function(e) {
				if (!mouseIsDown) {
					if (media.muted) {
						positionVolumeHandle(0);
						mute.removeClass('mejs-mute').addClass('mejs-unmute');
					} else {
						positionVolumeHandle(media.volume);
						mute.removeClass('mejs-unmute').addClass('mejs-mute');
					}
				}
			}, false);

			if (t.container.is(':visible')) {
				// Set initial volume
				positionVolumeHandle(player.options.startVolume);

				// Mutes the media and sets the volume icon muted if the initial volume is set to 0
                                if (player.options.startVolume === 0) {
                                  media.setMuted(true);
                                }

                                // Set start volume.
				media.setVolume(player.options.startVolume);
			}
		}
	});
	
})(mejs.$);

(function($) {

	$.extend(mejs.MepDefaults, {
		newWindowCallback: function() { return '';},
		fullscreenText: 'Fullscreen'
	});

	$.extend(MediaElementPlayer.prototype, {

		isFullScreen: false,

		isNativeFullScreen: false,

		isInIframe: false,

		buildfullscreen: function(player, controls, layers, media) {

			player.isInIframe = (window.location != window.parent.location);

			// Native
			if (mejs.MediaFeatures.hasTrueNativeFullScreen) {

				// Chrome doesn't always fire this in an iframe
				var func = function(e) {
					if (player.isFullScreen) {
						if (mejs.MediaFeatures.isFullScreen()) {
							player.isNativeFullScreen = true;
							// Reset the controls once we are fully in full screen
							player.setControlsSize();
						} else {
							player.isNativeFullScreen = false;
							// When a user presses ESC make sure to put the player back into place
							player.exitFullScreen();
						}
					}
				};

				if (mejs.MediaFeatures.hasMozNativeFullScreen) {
					player.globalBind(mejs.MediaFeatures.fullScreenEventName, func);
				} else {
					player.container.bind(mejs.MediaFeatures.fullScreenEventName, func);
				}
			}

			var t = this,
				normalHeight = 0,
				normalWidth = 0,
				container = player.container,
				fullscreenBtn =
					$('<div class="mejs-button mejs-fullscreen-button">' +
						'<button type="button" aria-controls="' + t.id + '" title="' + t.options.fullscreenText + '" aria-label="' + t.options.fullscreenText + '"></button>' +
					'</div>')
					.appendTo(controls);


                                fullscreenBtn.click(function() {
                                        var isFullScreen = (mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || player.isFullScreen;

                                        if (isFullScreen) {
                                                player.exitFullScreen();
                                        } else {
                                                player.enterFullScreen();
                                        }
                                });

			player.fullscreenBtn = fullscreenBtn;

			t.globalBind('keydown',function (e) {
				if (((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen()) || t.isFullScreen) && e.keyCode == 27) {
					player.exitFullScreen();
				}
			});

		},

		cleanfullscreen: function(player) {
			player.exitFullScreen();
		},

        containerSizeTimeout: null,

		enterFullScreen: function() {

			var t = this;
                        
			// Set it to not show scroll bars so 100% will work
                        $(document.documentElement).addClass('mejs-fullscreen');
                        
			// Store sizing
			normalHeight = t.container.height();
			normalWidth = t.container.width();

			// Attempt to do true fullscreen
                        if (mejs.MediaFeatures.hasTrueNativeFullScreen) {

                                mejs.MediaFeatures.requestFullScreen(t.container[0]);

                                if (t.isInIframe) {
                                        // Sometimes exiting from fullscreen doesn't work
                                        setTimeout(function checkFullscreen() {

                                                if (t.isNativeFullScreen) {

                                                        // Check if the video is suddenly not really fullscreen
                                                        if ($(window).width() !== screen.width) {
                                                                // manually exit
                                                                t.exitFullScreen();
                                                        } else {
                                                                // test again
                                                                setTimeout(checkFullscreen, 500);
                                                        }
                                                }


                                        }, 500);
                                }

                        } else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
                                t.media.webkitEnterFullscreen();
                                return;
                        }
                                
			// Check for iframe launch
			if (t.isInIframe) {
				var url = t.options.newWindowCallback(this);


				if (url !== '') {

					// Launch immediately
					if (!mejs.MediaFeatures.hasTrueNativeFullScreen) {
						t.pause();
						window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
						return;
					} else {
						setTimeout(function() {
							if (!t.isNativeFullScreen) {
								t.pause();
								window.open(url, t.id, 'top=0,left=0,width=' + screen.availWidth + ',height=' + screen.availHeight + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
							}
						}, 250);
					}
				}

			}

			// Full window code

			// Make full size
			t.container
				.addClass('mejs-container-fullscreen')
				.width('100%')
				.height('100%');

			// Only needed for safari 5.1 native full screen, can cause display issues elsewhere
                        t.containerSizeTimeout = setTimeout(function() {
                                t.container.css({width: '100%', height: '100%'});
                                t.setControlsSize();
                        }, 500);

                        t.$media
                                .width('100%')
                                .height('100%');

			t.layers.children('div')
				.width('100%')
				.height('100%');

			if (t.fullscreenBtn) {
				t.fullscreenBtn
					.removeClass('mejs-fullscreen')
					.addClass('mejs-unfullscreen');
			}

			t.setControlsSize();
			t.isFullScreen = true;
                        
                        t.container.find('.mejs-captions-text').css('font-size', screen.width / t.width * 1.00 * 100 + '%');
                        t.container.find('.mejs-captions-position').css('bottom', '45px');
		},

		exitFullScreen: function() {

			var t = this;
                        
                        // Prevent container from attempting to stretch a second time
                        clearTimeout(t.containerSizeTimeout);

			// Come out of native fullscreen
			if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() || t.isFullScreen)) {
				mejs.MediaFeatures.cancelFullScreen();
			}

			// Restore scroll bars to document
                        $(document.documentElement).removeClass('mejs-fullscreen');

			t.container
				.removeClass('mejs-container-fullscreen')
				.width(normalWidth)
				.height(normalHeight);

                        t.$media
                                .width(normalWidth)
                                .height(normalHeight);

			t.layers.children('div')
				.width(normalWidth)
				.height(normalHeight);

			t.fullscreenBtn
				.removeClass('mejs-unfullscreen')
				.addClass('mejs-fullscreen');

			t.setControlsSize();
			t.isFullScreen = false;
                        
                        t.container.find('.mejs-captions-text').css('font-size','');
                        t.container.find('.mejs-captions-position').css('bottom', '');
		}  
	});

})(mejs.$);

(function($) {

	// Add extra default options 
	$.extend(mejs.MepDefaults, {
		// This will automatically turn on a <track>
		startLanguage: '',

		tracksText: 'Captions/Subtitles',
		
		// Option to remove the [cc] button when no <track kind="subtitles"> are present
		hideCaptionsButtonWhenEmpty: true,

		// If true and we only have one track, change captions to popup
		toggleCaptionsButtonWhenOnlyOne: true,
                
                // Caption style options
                captionColor: "#FFFFFF",
		captionSize: "24px",
		captionBackground : "black",
		captionFont: "Arial",
	});

	$.extend(MediaElementPlayer.prototype, {
	
		hasChapters: false,

		buildtracks: function(player, controls, layers, media) {
			if (player.tracks.length == 0)
				return;

			var t = this, 
				i, 
				options = '';

                        // If browser will do native captions, prefer mejs captions, loop through tracks and hide
			if (t.domNode.textTracks) {
				for (var i = t.domNode.textTracks.length - 1; i >= 0; i--) {
					t.domNode.textTracks[i].mode = "hidden";
				}
			}
			player.chapters = 
					$('<div class="mejs-chapters mejs-layer"></div>')
						.prependTo(layers).hide();
			player.captions = 
					$('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position mejs-captions-position-hover"><span class="mejs-captions-text"></span></div></div>')
						.prependTo(layers).hide();
			player.captionsText = player.captions.find('.mejs-captions-text');
			player.captionsButton = 
					$('<div class="mejs-button mejs-captions-button">'+
						'<button type="button" aria-controls="' + t.id + '" title="' + t.options.tracksText + '" aria-label="' + t.options.tracksText + '"></button>'+
						'<div class="mejs-captions-selector">'+
							'<ul>'+
								'<li>'+
									'<input type="radio" name="' + player.id + '_captions" id="' + player.id + '_captions_none" value="none" checked="checked" />' +
									'<label for="' + player.id + '_captions_none">' + 'None' +'</label>'+
								'</li>'	+
							'</ul>'+
						'</div>'+
					'</div>')
						.appendTo(controls);
			
						
			var subtitleCount = 0;
			for (i=0; i<player.tracks.length; i++) {
				if (player.tracks[i].kind == 'subtitles') {
					subtitleCount++;
				}
			}

			// If only one language then just make the button a toggle
			if (t.options.toggleCaptionsButtonWhenOnlyOne && subtitleCount == 1){
				// Click
				player.captionsButton.on('click',function() {
					if (player.selectedTrack == null) {
						var lang = player.tracks[0].srclang;
					} else {
						var lang = 'none';
					}
					player.setTrack(lang);
				});
			} else {
				// Hover
				player.captionsButton.hover(function() {
					$(this).find('.mejs-captions-selector').css('visibility','visible');
				}, function() {
					$(this).find('.mejs-captions-selector').css('visibility','hidden');
				})

				// Handle clicks to the language radio buttons
				.on('click','input[type=radio]',function() {
					lang = this.value;
					player.setTrack(lang);
				});

			}

			if (!player.options.alwaysShowControls) {
				// Move with controls
				player.container
					.bind('controlsshown', function () {
						// Push captions above controls
						player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');

					})
					.bind('controlshidden', function () {
						if (!media.paused) {
							// Move back to normal place
							player.container.find('.mejs-captions-position').removeClass('mejs-captions-position-hover');
						}
					});
			} else {
				player.container.find('.mejs-captions-position').addClass('mejs-captions-position-hover');
			}

			player.trackToLoad = -1;
			player.selectedTrack = null;
			player.isLoadingTrack = false;

			

			// Add to list
			for (i=0; i<player.tracks.length; i++) {
				if (player.tracks[i].kind == 'subtitles') {
					player.addTrackButton(player.tracks[i].srclang, player.tracks[i].label);
				}
			}

			// Start loading tracks
			player.loadNextTrack();


			media.addEventListener('timeupdate',function(e) {
				player.displayCaptions();
			}, false);

			media.addEventListener('loadedmetadata', function(e) {
				player.displayChapters();
			}, false);

			player.container.hover(
				function () {
					// Chapters
					if (player.hasChapters) {
						player.chapters.css('visibility','visible');
						player.chapters.fadeIn(200).height(player.chapters.find('.mejs-chapter').outerHeight());
					}
				},
				function () {
					if (player.hasChapters && !media.paused) {
						player.chapters.fadeOut(200, function() {
							$(this).css('visibility','hidden');
							$(this).css('display','block');
						});
					}
				});
				
			// Check for autoplay
			if (player.node.getAttribute('autoplay') !== null) {
				player.chapters.css('visibility','hidden');
			}
		},
		
		setTrack: function(lang){
		
			var t = this,
				i;
		
			if (lang == 'none') {
				t.selectedTrack = null;
				t.captionsButton.removeClass('mejs-captions-enabled');
			} else {
				for (i=0; i<t.tracks.length; i++) {
					if (t.tracks[i].srclang == lang) {
						if (t.selectedTrack == null)
						    t.captionsButton.addClass('mejs-captions-enabled');
						t.selectedTrack = t.tracks[i];
						t.captions.attr('lang', t.selectedTrack.srclang);
						t.displayCaptions();
						break;
					}
				}
			}
		},

		loadNextTrack: function() {
			var t = this;

			t.trackToLoad++;
			if (t.trackToLoad < t.tracks.length) {
				t.isLoadingTrack = true;
				t.loadTrack(t.trackToLoad);
			} else {
				t.isLoadingTrack = false;
				
				t.checkForTracks();	
			}
		},

		loadTrack: function(index){
			var
				t = this,
				track = t.tracks[index],
				after = function() {

					track.isLoaded = true;

					// Create button
					t.enableTrackButton(track.srclang, track.label);

					t.loadNextTrack();

				};


			$.ajax({
				url: track.src,
				dataType: "text",
				success: function(d) {

					// Parse the loaded file
					if (typeof d == "string" && (/<tt\s+xml/ig).exec(d)) {
						track.entries = mejs.TrackFormatParser.dfxp.parse(d);					
					} else {	
						track.entries = mejs.TrackFormatParser.webvvt.parse(d);
					}
					
					after();

					if (track.kind == 'chapters') {
						t.media.addEventListener('play', function(e) {
							if (t.media.duration > 0) {
								t.displayChapters(track);
							}
						}, false);
					}
					
					if (track.kind == 'slides') {
						t.setupSlides(track);
					}					
				},
				error: function() {
					t.loadNextTrack();
				}
			});
		},

		enableTrackButton: function(lang, label) {
			var t = this;
			
			if (label === '') {
				label = mejs.language.codes[lang] || lang;
			}			

			t.captionsButton
				.find('input[value=' + lang + ']')
					.prop('disabled',false)
				.siblings('label')
					.html( label );

			// Auto select
			if (t.options.startLanguage == lang) {
				$('#' + t.id + '_captions_' + lang).click();
			}

			t.adjustLanguageBox();
		},

		addTrackButton: function(lang, label) {
			var t = this;
			if (label === '') {
				label = mejs.language.codes[lang] || lang;
			}

			t.captionsButton.find('ul').append(
				$('<li>'+
					'<input type="radio" name="' + t.id + '_captions" id="' + t.id + '_captions_' + lang + '" value="' + lang + '" disabled="disabled" />' +
					'<label for="' + t.id + '_captions_' + lang + '">' + label + ' (loading)' + '</label>'+
				'</li>')
			);

			t.adjustLanguageBox();

			// Remove this from the dropdownlist (if it exists)
			t.container.find('.mejs-captions-translations option[value=' + lang + ']').remove();
		},

		adjustLanguageBox:function() {
			var t = this;
			// Adjust the size of the outer box
			t.captionsButton.find('.mejs-captions-selector').height(
				t.captionsButton.find('.mejs-captions-selector ul').outerHeight(true) +
				t.captionsButton.find('.mejs-captions-translations').outerHeight(true)
			);
		},
		
		checkForTracks: function() {
			var
				t = this,
				hasSubtitles = false;
			
			// Check if any subtitles
			if (t.options.hideCaptionsButtonWhenEmpty) {
				for (i=0; i<t.tracks.length; i++) {
					if (t.tracks[i].kind == 'subtitles') {
						hasSubtitles = true;
						break;
					}
				}	
					
				if (!hasSubtitles) {
					t.captionsButton.hide();
					t.setControlsSize();
				}													
			}		
		},

		displayCaptions: function() {

			if (typeof this.tracks == 'undefined')
				return;

			var
				t = this,
				i,
				track = t.selectedTrack;

			if (track != null && track.isLoaded) {
				for (i=0; i<track.entries.times.length; i++) {
					if (t.currentTime >= track.entries.times[i].start && t.currentTime <= track.entries.times[i].stop){
						t.captionsText.html(track.entries.text[i]);
						t.captions.show().height(0);
						return;
					}
				}
				t.captions.hide();
			} else {
				t.captions.hide();
			}
		},

		displayChapters: function() {
			var 
				t = this,
				i;

			for (i=0; i<t.tracks.length; i++) {
				if (t.tracks[i].kind == 'chapters' && t.tracks[i].isLoaded) {
					t.drawChapters(t.tracks[i]);
					t.hasChapters = true;
					break;
				}
			}
		},

		drawChapters: function(chapters) {
			var 
				t = this,
				i,
				dur,
				percent = 0,
				usedPercent = 0;

			t.chapters.empty();

			for (i=0; i<chapters.entries.times.length; i++) {
				dur = chapters.entries.times[i].stop - chapters.entries.times[i].start;
				percent = Math.floor(dur / t.media.duration * 100);
				if (percent + usedPercent > 100 || // too large
					i == chapters.entries.times.length-1 && percent + usedPercent < 100) // not going to fill it in
					{
					percent = 100 - usedPercent;
				}

				t.chapters.append( $(
					'<div class="mejs-chapter" rel="' + chapters.entries.times[i].start + '" style="left: ' + usedPercent.toString() + '%;width: ' + percent.toString() + '%;">' + 
						'<div class="mejs-chapter-block' + ((i==chapters.entries.times.length-1) ? ' mejs-chapter-block-last' : '') + '">' + 
							'<span class="ch-title">' + chapters.entries.text[i] + '</span>' + 
							'<span class="ch-time">' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].start) + '&ndash;' + mejs.Utility.secondsToTimeCode(chapters.entries.times[i].stop) + '</span>' + 
						'</div>' +
					'</div>'));
				usedPercent += percent;
			}

			t.chapters.find('div.mejs-chapter').click(function() {
				t.media.setCurrentTime( parseFloat( $(this).attr('rel') ) );
				if (t.media.paused) {
					t.media.play(); 
				}
			});

			t.chapters.show();
		},
                
                buildcaptioncustomiser: function (player, controls, layers, media) {
                    var $caption_text_container = $('.mejs-captions-text'),
                        $caption_container = $caption_text_container.parent();

                    if(player.options.captionBackground){
                        $caption_container.css("background",player.options.captionBackground);
                        $caption_text_container.css("background","none");
                    }
                    $caption_text_container.css("font-family",player.options.captionFont);
                    $caption_text_container.css("font-size",player.options.captionSize);
                    $caption_text_container.css("color",player.options.captionColor);

                }
	});



	mejs.language = {
		codes:  {
			af:'Afrikaans',
			sq:'Albanian',
			ar:'Arabic',
			be:'Belarusian',
			bg:'Bulgarian',
			ca:'Catalan',
			zh:'Chinese',
			'zh-cn':'Chinese Simplified',
			'zh-tw':'Chinese Traditional',
			hr:'Croatian',
			cs:'Czech',
			da:'Danish',
			nl:'Dutch',
			en:'English',
			et:'Estonian',
			tl:'Filipino',
			fi:'Finnish',
			fr:'French',
			gl:'Galician',
			de:'German',
			el:'Greek',
			ht:'Haitian Creole',
			iw:'Hebrew',
			hi:'Hindi',
			hu:'Hungarian',
			is:'Icelandic',
			id:'Indonesian',
			ga:'Irish',
			it:'Italian',
			ja:'Japanese',
			ko:'Korean',
			lv:'Latvian',
			lt:'Lithuanian',
			mk:'Macedonian',
			ms:'Malay',
			mt:'Maltese',
			no:'Norwegian',
			fa:'Persian',
			pl:'Polish',
			pt:'Portuguese',
			ro:'Romanian',
			ru:'Russian',
			sr:'Serbian',
			sk:'Slovak',
			sl:'Slovenian',
			es:'Spanish',
			sw:'Swahili',
			sv:'Swedish',
			th:'Thai',
			tr:'Turkish',
			uk:'Ukrainian',
			vi:'Vietnamese',
			cy:'Welsh',
			yi:'Yiddish'
		}
	};

	/*
	Parses WebVVT format which should be formatted as
	================================
	WEBVTT
	
	1
	00:00:01,1 --> 00:00:05,000
	A line of text

	2
	00:01:15,1 --> 00:02:05,000
	A second line of text
	
	===============================

	Adapted from: http://www.delphiki.com/html5/playr
	*/
	mejs.TrackFormatParser = {
		webvvt: {
			// Match start "chapter-"
			pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/,
			pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,

			parse: function(trackText) {
				var 
					i = 0,
					lines = mejs.TrackFormatParser.split2(trackText, /\r?\n/),
					entries = {text:[], times:[]},
					timecode,
					text;
				for(; i<lines.length; i++) {
					// Check for the line number
					if (this.pattern_identifier.exec(lines[i])){
						// Skip to the next line where the start --> end time code should be
						i++;
						timecode = this.pattern_timecode.exec(lines[i]);				

						if (timecode && i<lines.length){
							i++;
							// Grab all the text that follows
							text = lines[i];
							i++;
							while(lines[i] !== '' && i<lines.length){
								text = text + '\n' + lines[i];
								i++;
							}
							text = $.trim(text).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
							// Text is in a different array so I can use .join
							entries.text.push(text);
							entries.times.push(
							{
								start: (mejs.Utility.convertSMPTEtoSeconds(timecode[1]) == 0) ? 0.200 : mejs.Utility.convertSMPTEtoSeconds(timecode[1]),
								stop: mejs.Utility.convertSMPTEtoSeconds(timecode[3]),
								settings: timecode[5]
							});
						}
					}
				}
				return entries;
			}
		},

                dfxp: {
			parse: function(trackText) {
				trackText = $(trackText).filter("tt");
				var 
					i = 0,
					container = trackText.children("div").eq(0),
					lines = container.find("p"),
					styleNode = trackText.find("#" + container.attr("style")),
					styles,
					begin,
					end,
					text,
					entries = {text:[], times:[]};


				if (styleNode.length) {
					var attributes = styleNode.removeAttr("id").get(0).attributes;
					if (attributes.length) {
						styles = {};
						for (i = 0; i < attributes.length; i++) {
							styles[attributes[i].name.split(":")[1]] = attributes[i].value;
						}
					}
				}

				for(i = 0; i<lines.length; i++) {
					var style;
					var _temp_times = {
						start: null,
						stop: null,
						style: null
					};
					if (lines.eq(i).attr("begin")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("begin"));
					if (!_temp_times.start && lines.eq(i-1).attr("end")) _temp_times.start = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i-1).attr("end"));
					if (lines.eq(i).attr("end")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i).attr("end"));
					if (!_temp_times.stop && lines.eq(i+1).attr("begin")) _temp_times.stop = mejs.Utility.convertSMPTEtoSeconds(lines.eq(i+1).attr("begin"));
					if (styles) {
						style = "";
						for (var _style in styles) {
							style += _style + ":" + styles[_style] + ";";					
						}
					}
					if (style) _temp_times.style = style;
					if (_temp_times.start == 0) _temp_times.start = 0.200;
					entries.times.push(_temp_times);
					text = $.trim(lines.eq(i).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
					entries.text.push(text);
					if (entries.times.start == 0) entries.times.start = 2;
				}
				return entries;
			}
		},
		split2: function (text, regex) {

                        return text.split(regex);
		}
	};	

})(mejs.$);

/*
* ContextMenu Plugin
* 
*
*/

(function($) {

$.extend(mejs.MepDefaults,
	{ 'contextMenuItems': [
		// demo of a fullscreen option
		{ 
			render: function(player) {
				
				// check for fullscreen plugin
				if (typeof player.enterFullScreen == 'undefined')
					return null;
			
				if (player.isFullScreen) {
					return 'Turn Off Fullscreen';
				} else {
					return 'Go Fullscreen';
				}
			},
			click: function(player) {
				if (player.isFullScreen) {
					player.exitFullScreen();
				} else {
					player.enterFullScreen();
				}
			}
		}
		,
		// demo of a mute/unmute button
		{ 
			render: function(player) {
				if (player.media.muted) {
					return 'Unmute';
				} else {
					return 'Mute';
				}
			},
			click: function(player) {
				if (player.media.muted) {
					player.setMuted(false);
				} else {
					player.setMuted(true);
				}
			}
		},
		// separator
		{
			isSeparator: true
		}
		,
		// demo of simple download video
		{ 
			render: function(player) {
				return 'Download Video File';
			},
			click: function(player) {
				window.location.href = player.media.currentSrc;
			}
		}	
	]}
);


	$.extend(MediaElementPlayer.prototype, {
		buildcontextmenu: function(player, controls, layers, media) {
			
			// create context menu
			player.contextMenu = $('<div class="mejs-contextmenu"></div>')
								.appendTo($('body'))
								.hide();
			
			// create events for showing context menu
			player.container.bind('contextmenu', function(e) {
				if (player.isContextMenuEnabled) {
					e.preventDefault();
					player.renderContextMenu(e.clientX-1, e.clientY-1);
					return false;
				}
			});
			player.container.bind('click', function() {
				player.contextMenu.hide();
			});	
			player.contextMenu.bind('mouseleave', function() {

				//
				player.startContextMenuTimer();
				
			});		
		},

		cleancontextmenu: function(player) {
			player.contextMenu.remove();
		},
		
		isContextMenuEnabled: true,
		enableContextMenu: function() {
			this.isContextMenuEnabled = true;
		},
		disableContextMenu: function() {
			this.isContextMenuEnabled = false;
		},
		
		contextMenuTimeout: null,
		startContextMenuTimer: function() {
			//
			
			var t = this;
			
			t.killContextMenuTimer();
			
			t.contextMenuTimer = setTimeout(function() {
				t.hideContextMenu();
				t.killContextMenuTimer();
			}, 750);
		},
		killContextMenuTimer: function() {
			var timer = this.contextMenuTimer;
			
			//
			
			if (timer != null) {				
				clearTimeout(timer);
				delete timer;
				timer = null;
			}
		},		
		
		hideContextMenu: function() {
			this.contextMenu.hide();
		},
		
		renderContextMenu: function(x,y) {
			
			// alway re-render the items so that things like "turn fullscreen on" and "turn fullscreen off" are always written correctly
			var t = this,
				html = '',
				items = t.options.contextMenuItems;
			
			for (var i=0, il=items.length; i<il; i++) {
				
				if (items[i].isSeparator) {
					html += '<div class="mejs-contextmenu-separator"></div>';
				} else {
				
					var rendered = items[i].render(t);
				
					// render can return null if the item doesn't need to be used at the moment
					if (rendered != null) {
						html += '<div class="mejs-contextmenu-item" data-itemindex="' + i + '" id="element-' + (Math.random()*1000000) + '">' + rendered + '</div>';
					}
				}
			}
			
			// position and show the context menu
			t.contextMenu
				.empty()
				.append($(html))
				.css({top:y, left:x})
				.show();
				
			// bind events
			t.contextMenu.find('.mejs-contextmenu-item').each(function() {
							
				// which one is this?
				var $dom = $(this),
					itemIndex = parseInt( $dom.data('itemindex'), 10 ),
					item = t.options.contextMenuItems[itemIndex];
				
				// bind extra functionality?
				if (typeof item.show != 'undefined')
					item.show( $dom , t);
				
				// bind click action
				$dom.click(function() {			
					// perform click action
					if (typeof item.click != 'undefined')
						item.click(t);
					
					// close
					t.contextMenu.hide();				
				});				
			});	
			
			// stop the controls from hiding
			setTimeout(function() {
				t.killControlsTimer('rev3');	
			}, 100);
						
		}
	});
	
})(mejs.$);
